package com.shsoft.task;

import com.shsoft.entity.HardWareInfo;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class NetTask implements Runnable{
    @Override
    public void run() {
        long lastReceiveByteCounts = 0;
        long lastSendByteCounts = 0;
        while (true){
            try{
                ProcessBuilder processBuilder = new ProcessBuilder();
                processBuilder.command("netstat", "-e");
                Process process = processBuilder.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                int index = 0;
                while ((line = reader.readLine()) != null) {
                    if(index == 4){
                        String[] s = line.replaceAll("\\s+", " ").split(" ");
                        if(lastReceiveByteCounts != 0 || lastSendByteCounts != 0){
                            HardWareInfo.netDownloadSpeed = ((Long.parseLong(s[1]) - lastReceiveByteCounts) / 2.0f / 1024);
                            HardWareInfo.netUploadSpeed = ((Long.parseLong(s[2]) - lastSendByteCounts) / 2.0f / 1024);
                        }
                        lastReceiveByteCounts = Long.parseLong(s[1]);
                        lastSendByteCounts = Long.parseLong(s[2]);
                    }
                    index++;
                }
                reader.close();
                Thread.sleep(2000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
